<template>
  <div>
    <div>
      <el-input 
        placeholder="标题搜索" 
        style="width: 300px;margin: 0 0 20px 0;" 
        prefix-icon="el-icon-search"
        v-model="input"
        @input="handleInput"
      ></el-input>
      <el-popconfirm
        title="确定要删除选中的论文？删除后无法恢复！"
        @onConfirm="handleDeleteMultiple"
      >
        <el-button 
          slot="reference"
          :disabled="multipleSelection.length === 0" 
          type="danger"
          size="smail"
          icon="el-icon-delete"
          style="margin-left: 20px;"
        >删除选中</el-button>
      </el-popconfirm>
      <el-popconfirm
        :title="`确定要撤回选中的论文？`"
        @onConfirm="handleRevocationMultiple"
        v-if="status === 0"
      >
        <el-button 
          slot="reference"
          :disabled="multipleSelection.length === 0" 
          type="warning"
          size="smail"
          icon="el-icon-delete"
          style="margin-left: 20px;"
        >撤回选中</el-button>
      </el-popconfirm>
      <el-popconfirm
        :title="`确定要发表选中的论文？`"
        @onConfirm="handlePublishMultiple"
        v-if="status === 1"
      >
        <el-button 
          slot="reference"
          :disabled="multipleSelection.length === 0" 
          type="warning"
          size="smail"
          icon="el-icon-delete"
          style="margin-left: 20px;"
        >发表选中</el-button>
      </el-popconfirm>
    </div>
    <el-table
      :data="releasedData"
      border
      v-loading="loading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55px"
      >
      </el-table-column>
      <el-table-column
        label="ID"
        prop="id"
        align="center"
        header-align="center"
        width="200px"
      >
        <template slot-scope="{ row }">
          {{ row.id }}
        </template>
      </el-table-column>
      <el-table-column
        label="标题"
        prop="title"
        align="center"
        header-align="center"
        width="200px"
        show-overflow-tooltip
      >
        <template slot-scope="{ row }">
          <span v-html="row.title"></span>
        </template>
      </el-table-column>
      <el-table-column
        label="作者"
        prop="authers"
        align="center"
        header-align="center"
        width="120px"
        show-overflow-tooltip
      >
        <template slot-scope="{ row }">
          <span>{{ join(row.authers, '、') }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="发表时间"
        prop="publishedTime"
        align="center"
        header-align="center"
        width="150px"
      >
        <template slot-scope="{ row }">
          <span>{{ formatDate(row.publishedTime, 'yyyy-MM') }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="最后修改"
        prop="modifyTime"
        align="center"
        header-align="center"
        width="150px"
      >
        <template slot-scope="{ row }">
          <span>{{ formatDate(row.modifyTime, 'yyyy-MM-dd') }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="关键字"
        prop="keywords"
        align="center"
        header-align="center"
        width="200px"
        show-overflow-tooltip
      >
        <template slot-scope="{ row }">
          <span>{{ join(row.keywords, '、') }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="简介"
        prop="summary"
        align="center"
        header-align="center"
        width="300px"
      >
        <template slot-scope="{ row }">
          <el-tooltip popper-class="popper" :visible-arrow="false">
            <span slot="content">{{ row.summary }}</span>
            <span class="summary">{{ row.summary }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column
        label="下载量"
        prop="downloads"
        align="center"
        header-align="center"
        width="70px"
      >
        <template slot-scope="{ row }">
          <span>{{ row.downloads }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="文件名"
        prop="fileName"
        align="center"
        header-align="center"
        width="200px"
        show-overflow-tooltip
      >
        <template slot-scope="{ row }">
          <span>{{ row.fileName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        :width="status === 2 ? '160px' : '100px'"
        fixed="right"
        align="center"
        header-align="center"
      >
        <template slot-scope="{ row }">
          <el-button type="primary" size="mini" @click="handleGoEditPage(row)">修改</el-button>
          <el-button type="success" size="mini" v-if="status === 2" @click="fileName = row.fileName; id = row.id; showDialog = true">发表</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      style="margin: 20px 0;"
      :page-size="pageSize"
      :total="total"
      :current-page.sync="pageIndex"
      @current-change="handleChangePage"
      :disabled="input !== ''"
    >
    </el-pagination>
    <el-dialog
      :visible.sync="showDialog"
      title="上传论文的PDF文件"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <div style="margin-bottom: 20px;">
        将本地PDF文件名改成：<el-tag v-if="fileName">{{ fileName }}</el-tag>
      </div>
      <el-upload
        action=""
        accept="application/pdf"
        ref="upload"
        :multiple="false"
        :auto-upload="false"
        :limit="1"
        :http-request="startUpload"
      >
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="$refs.upload.submit()" :loading="loadingUpload">开始上传</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getAll, searchTitle, deletes, revocation, publish } from '../api/v1/paperManagement'
import { upload } from '../api/v1/paperPdf'
import { join, formatDate, debounce } from '../libs/tools'
export default {
  name: 'Released',
  props: {
    status: Number
  },
  data() {
    return {
      pageIndex: 1,
      pageSize: 10,
      releasedData: [],
      input: '',
      loading: false,
      loadingUpload: false,
      multipleSelection: [],
      total: 0,
      showDialog: false,
      fileName: '',
      id: ''
    }
  },
  methods: {
    startUpload({ file }) {
      if(file.name !== this.fileName) {
        this.$message.error(`文件名错误，请将文件名修改成<${this.fileName}>再上传!`)
      } else if (file.type !== 'application/pdf') {
        this.$message.error(`文件类型错误，请选择PDF文件!`)
      } else if (file.size / 1024 / 1024 > 100) {
        this.$message.error(`文件太大，请上传小于100MB的文件`)
      } else {
        this.loadingUpload = true
        const formData = new FormData()
        formData.append(file.name, file)
        upload(formData).then(res => {
          publish([this.id]).then(res => {
            this.$message.success('发表论文成功！')
            this.loadingUpload = false
            this.showDialog = false
            this.getData(this.status, 1, this.pageSize)
          }).catch(e => {
            this.$notify({
              title: '上传结果',
              message: '上传论文失败！',
              type: 'error',
              duration: 0
            })
            this.loadingUpload = false
            this.showDialog = false
          })
        }).catch(e => {
          this.$notify({
            title: '上传结果',
            message: '上传PDF文件失败！',
            type: 'error',
            duration: 0
          })
          this.loadingUpload = false
          this.showDialog = false
        })
      }
    },
    join,
    formatDate,
    // 去往修改页面
    handleGoEditPage(row) {
      sessionStorage.setItem('paper', JSON.stringify(row))
      this.$router.push({ path: 'paper/edit'})
    },
    /**
     * @description 页码改变时触发
     */
    handleChangePage(pageIndex) {
      this.getData(this.status, pageIndex, this.pageSize)
    },
    /**
     * @description 删除选中的论文
     */
    handleDeleteMultiple() {
      if(this.multipleSelection.length !== 0) {
        const ids = this.multipleSelection.map(item => item.id)
        deletes(ids).then(res => {
          if(res.data && res.data.msg === 'Ok') {
            this.$message.success('删除成功！')
            this.multipleSelection = []
            this.getData(this.status, 1, this.pageSize)
          } else {
            this.$message.error('删除失败!')
          }
        }).catch(e => {
          this.$message.error('删除失败!')
          console.log(e.message)
        })
      }
    },
    /**
     * @description 撤回选中的论文
     */
    handleRevocationMultiple() {
      if(this.multipleSelection.length !== 0) {
        const ids = this.multipleSelection.map(item => item.id)
        revocation(ids).then(res => {
          console.log(res)
          if(res.data && res.data.msg === 'Ok') {
            this.$message.success('撤回成功！')
            this.multipleSelection = []
            this.getData(this.status, 1, this.pageSize)
          } else {
            this.$message.error('撤回失败!')
          }
        }).catch(e => {
          this.$message.error('撤回失败!')
          console.log(e.message)
        })
      }
    },
    /**
     * @description 发布选中的论文
     */
    handlePublishMultiple() {
      if(this.multipleSelection.length !== 0) {
        const ids = this.multipleSelection.map(item => item.id)
        publish(ids).then(res => {
          console.log(res.data)
          this.$message.success('发表成功！')
          this.multipleSelection = []
          this.getData(this.status, 1, this.pageSize)
        }).catch(e => {
          console.log(e.response)
          if(e.response && e.response.data === ' Error: The paper name is duplicate or does not exist (Error 2).') {
            this.$message.error('发表失败：文件名重复或者文件不存在！')
          }
          if((e + '').includes('code 500')) {
            this.$message.error('发表失败：文件名重复！')
          }
        })
      }
    },
    /**
     * @description 选中论文时触发
     * @param { array } val
     */
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    /**
     * @description 分页获取状态为0的论文
     * @param { Number } status 状态
     * @param { Number } pageIndex 页码
     * @param { Number } [pageSize = 10] 页大小
     */
    getData(status, pageIndex, pageSize) {
      this.loading = true
      getAll(status, pageIndex, pageSize).then(res => {
        this.loading = false
        this.releasedData = res.data.results
        this.total = res.data.resultNumber
      }).catch(e => {
        this.loading = false
        console.log(e)
      })
    },
    /**
     * @description 搜索论文
     */
    getDataBySearch(value) {
      this.loading = true
      searchTitle(value, this.status, 100).then(res => {
        this.loading = false
        if(res.status === 200 && res.data && Array.isArray(res.data)) {
          this.releasedData = res.data
          this.total = res.data.length
        }
      }).catch(e => {
        this.loading = false
        this.releasedData = []
        this.total = 0
        console.log(e)
      })
    },
    // handleEnter: debounce(function (value) {
    //   console.log('handleEnter: ', value)
    //   if(value === '') {
    //     this.getData(this.status, 1, this.pageSize)
    //     return
    //   }
    //   this.getDataBySearch(value)
    // }),
    handleInput: debounce(function (value) {
      console.log('handleInput: ', value)
      if(value === '') {
        this.getData(this.status, 1, this.pageSize)
        return
      }
      this.getDataBySearch(value)
    })
  },
  created() {
    this.getData(this.status, 1, this.pageSize)
  },
  watch: {
    showDialog(n) {
      if(!n) {
        this.$refs.upload.clearFiles()
      }
    }
  },
}
</script>

<style scoped>
.summary {
  white-space: nowrap;
  text-overflow: ellipsis;
}



</style>